package org.shadow.process;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shadow.domain.HttpRequest;

//获取请求信息
public class HttpRequestProcess {

	private static Logger logger = LogManager.getLogger();

	private static final String REPLICE_TOKEN = "\\r\\n";

	public void process(final SelectionKey key, final Selector selector) {
		logger.info("HttpProcess process selectionKey is:{},thread name is:{}", key, Thread.currentThread().getName());
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		try {
			channel.read(buffer);
			buffer.flip();
			byte[] bytes = new byte[buffer.limit()];
			buffer.get(bytes);
			String headersStr = new String(bytes);
			logger.info("HttpProcess process request is:{}", headersStr);
			Map<String, String> requestMap = analyzeReq(headersStr);
			key.attach(convertRequest(requestMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Map<String, String> analyzeReq(String headData) {
		Map<String, String> requestMap = new HashMap<>();
		String[] tmpData = headData.split(REPLICE_TOKEN);
		for (int i = 0; i < tmpData.length; i++) {
			String reqParam = tmpData[i];
			if (i == 0 && reqParam.indexOf(":") < 0) {
				String[] reqParams = reqParam.split(" ");
				if (reqParams.length < 1) {
					continue;
				}
				requestMap.put("request-method", reqParams[0].trim());
				if (reqParams.length < 2) {
					continue;
				}
				String param = reqParams[1].trim();
				requestMap.put("request-page", param.substring(param.indexOf("/") + 1,
						param.indexOf("?") < 0 ? param.length() : param.indexOf("?")));
				if (reqParams.length < 3) {
					continue;
				}
				requestMap.put("request-version", reqParams[2].trim());
				if (tmpData[tmpData.length - 2].isEmpty()) {
					requestMap.put("query-string", tmpData[tmpData.length - 1]);
				}
			} else {
				String[] reqParams = reqParam.split(":");
				if (reqParams.length < 2) {
					continue;
				}
				requestMap.put(reqParams[0].toLowerCase(), reqParams[1].trim());
			}
		}

		logger.debug("HttpProcess process request map is:{}", requestMap);
		return requestMap;
	}

	private HttpRequest convertRequest(Map<String, String> requestMap) {
		HttpRequest request = new HttpRequest();
		request.setAccept(requestMap.get("accept"));
		request.setAcceptEncoding(requestMap.get("accept-encoding"));
		request.setAcceptLaguage(requestMap.get("accpet-language"));
		request.setConnection(requestMap.get("connection"));
		request.setCookie(requestMap.get("cookie"));
		request.setCacheControl(requestMap.get("cache-control"));
		request.setContentLength(requestMap.get("content-length"));
		request.setContentType(requestMap.get("content-type"));
		request.setHost(requestMap.get("host"));
		request.setMethod(requestMap.get("method"));
		request.setQueryString(requestMap.get("query-string"));
		request.setReferer(requestMap.get("referer"));
		request.setRequestPage(requestMap.get("request-page"));
		request.setUserAgent(requestMap.get("user-agent"));
		request.setVersion(requestMap.get("version"));
		return request;
	}

}
